import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import PetProducts from '@/views/PetProducts.vue';
import PetAdoption from '@/views/PetAdoption.vue';
import PetLost from '@/views/PetLost.vue';
import Forum from '@/views/Forum.vue';
import Profile from '@/views/Profile.vue';
import ShoppingCart from '@/views/ShoppingCart.vue';
// import CustomerService from '@/views/CustomerService.vue';
import PetAdoptionRegistration from '@/views/PetAdoptionRegistration.vue';
import PostDetail from '@/views/PostDetail.vue';
import ProfileEdit from '@/views/ProfileEdit.vue';
const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login // 默认加载登录页面
  },
  {
    path: '/home',
    name: 'Home',
    component: Home // 移除认证要求
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/pet-products',
    name: 'PetProducts',
    component: PetProducts,
    meta: { requiresAuth: true } // 仍需要认证
  },
  {
    path: '/pet-adoption',
    name: 'PetAdoption',
    component: PetAdoption,
    meta: { requiresAuth: true } // 仍需要认证
  },
  {
    path: '/profile/edit',
    name: 'ProfileEdit',
    component: () => import('@/views/ProfileEdit.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/pet-lost',
    name: 'PetLost',
    component: PetLost,
    meta: { requiresAuth: true } // 仍需要认证
  },
  {
    path: '/forum/post/:postId',
    name: 'PostDetail',
    component: PostDetail, 
    props: true
  },
  {
    path: '/forum',
    name: 'Forum',
    component: Forum,
    meta: { requiresAuth: true } // 仍需要认证
  },
    {
    path: '/forum/post/:postId',
    name: 'PostDetail',
    component: PostDetail, // 使用帖子详情页面组件
    props: true // 启用 props 传递
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { requiresAuth: true } // 仍需要认证
  },
  {
    path: '/shopping-cart',
    name: 'ShoppingCart',
    component: ShoppingCart,
    meta: { requiresAuth: true } // 仍需要认证
  },
  // {
  //   path: '/customer-service',
  //   name: 'CustomerService',
  //   component: CustomerService
  // },
  {
    path: '/Pet-AdoptionRegistration',
    name: 'PetAdoptionRegistration',
    component: PetAdoptionRegistration
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const token = localStorage.getItem('token');
    if (!token) {
      next('/'); // 如果需要认证但未登录，跳转到登录页面
    } else {
      next(); // 如果已登录，允许访问
    }
  } else {
    next(); // 对于不需要认证的路由，直接允许访问
  }
});

export default router;